package com.example.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
@Component
@ConfigurationProperties(prefix = "yy.jwt")
public class JwtUtils {
    /**
     * 密钥
     */
    private static final String SECRET = "yy666999yy";

    /**
     * 过期时间
     **/
    private static final long EXPIRATION = 86400;//单位为秒  一天:24*60*60

    /**
     * 生成用户token,设置token超时时间
     */
    public static String createToken(Integer id, String username) {
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("alg", "HS256");
        headerMap.put("typ", "JWT");

        HashMap<String, Object> userClaims = new HashMap<>();
        userClaims.put("id", id);
        userClaims.put("username", username);
        return JWT.create()
                .withHeader(headerMap)// 添加头部
                //可以将基本信息放到claims中
                .withClaim("user",userClaims)// user信息
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 校验token
     */
    public static boolean verifyToken(String token) {
        try{
            DecodedJWT jwt=JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    /**
     *  解析token
     *  返回UserMap对象
     */
    public static Map<String, Object> getUserOfToken(String token) throws JWTDecodeException {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Map<String, Claim> claims = decodedJWT.getClaims();

        return claims.get("user").asMap();
    }
}




